const db = uniCloud.database();
const cookie = require('cookie')

function makeToken() {
	let guid = ''
	for (let i = 1; i <= 32; i++) {
		const n = Math.floor(Math.random() * 16.0).toString(16)
		guid += n
	}
	return guid;
}

async function tokenCheck(this_) {
	const httpInfo = this_.getHttpInfo()
	const cookieData = cookie.parse(httpInfo.headers.cookie || '')
	if (!cookieData.token)
		return {
			mpserverlessComposedResponse: true,
			statusCode: 403,
			headers: {
				'content-type': 'application/json',
				'set-cookie': cookie.serialize('token', '', {
					path: "/",
				}),
			},
			body: JSON.stringify({
				msg: "token已失效"
			})
		}
	const collection = db.collection('admin');
	let userdata = (await collection.where({
		token: cookieData.token
	}).get()).data
	if (userdata.length == 0 || userdata[0].loginIp != this_.getHttpInfo().headers['x-real-ip'])
		return {
			mpserverlessComposedResponse: true,
			statusCode: 403,
			headers: {
				'content-type': 'application/json',
				'set-cookie': cookie.serialize('token', '', {
					path: "/",
				}),
			},
			body: JSON.stringify({
				msg: "token已失效"
			})
		}
	return userdata[0]
}
module.exports = {
	async login(parms) {
		const httpInfo = this.getHttpInfo()
		const cookieData = cookie.parse(httpInfo.headers.cookie || '')
		const collection = db.collection('admin');
		let userdata = (await collection.where({
			userid: parms.userid,
			password: parms.password
		}).get()).data
		if (userdata.length == 0) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				body: JSON.stringify({
					msg: "账户或密码错误"
				})
			}
		}
		let token = makeToken()
		let loginIp = this.getHttpInfo().headers['x-real-ip']
		await collection.where({
			userid: parms.userid,
			password: parms.password
		}).update({
			token: token,
			tokentime: new Date().getTime(),
			loginIp: loginIp
		})

		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			headers: {
				'content-type': 'application/json',
				'set-cookie': cookie.serialize('token', token, {
					maxAge: 60 * 60 * 24 * 7, //一周
					path: "/",
					SameSite: 'none'
				}),
			},
			body: JSON.stringify({
				_id: userdata[0]._id,
				userid: userdata[0].userid,
				token: token,
				loginIp: loginIp
			})
		}
	},
	async loginOut() {
		let userdata = await tokenCheck(this)
		if (userdata.power) {
			const collection = db.collection('admin');
			await collection.doc(userdata._id).update({
				token: ''
			})
		}
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			headers: {
				'content-type': 'application/json',
				'set-cookie': cookie.serialize('token', '', {
					maxAge: 60 * 60 * 24 * 7, //一周
					path: "/",
					SameSite: 'none'
				}),
			},
			body: JSON.stringify({
				code: 200
			})
		}
	},
	async cookieLogin() {
		const httpInfo = this.getHttpInfo()
		const cookieData = cookie.parse(httpInfo.headers.cookie || '')
		if (!cookieData.token) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				body: JSON.stringify({
					msg: "token不存在"
				})
			}
		}
		const collection = db.collection('admin');
		let userdata = (await collection.where({
			token: cookieData.token
		}).field({
			'userid': true,
			'token': true,
			'loginIp': true
		}).get()).data
		if (userdata.length == 0 || userdata[0].loginIp != this.getHttpInfo().headers['x-real-ip']) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				headers: {
					'content-type': 'application/json',
					'set-cookie': cookie.serialize('token', '', {
						path: "/",
					}),
				},
				body: JSON.stringify({
					msg: "token已失效"
				})
			}
		}
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(userdata[0])
		}
	},
	async addSwiper(parms) {
		let userdata = await tokenCheck(this)
		if (!userdata.power) {
			return userdata
		}
		if (!parms.type_id) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				body: JSON.stringify({
					msg: "缺少参数"
				})
			}
		}
		let type_id = parseInt(parms.type_id)
		const swiper = db.collection('swiper');
		let data = await swiper.add({
			"type_id": type_id,
			"vod_name": "待填写",
			"vod_info": "待填写",
			"vod_id": 0,
			"vod_img": "",
			"vod_img_small": "",
			"vod_index": (await swiper.where({
				type_id
			}).get()).data.length
		})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(data)
		}
	},
	async delSwiper(parms) {
		let userdata = await tokenCheck(this)
		if (!userdata.power) {
			return userdata
		}
		if (!parms._id) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				body: JSON.stringify({
					msg: "缺少参数"
				})
			}
		}
		let _id = parms._id
		const swiper = db.collection('swiper');
		let data = await swiper.doc(_id).remove();
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(data)
		}
	},
	async editSwiper(parms) {
		let userdata = await tokenCheck(this)
		if (!userdata.power) {
			return userdata
		}
		if (!parms._id || !parms.key || !parms.value) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				body: JSON.stringify({
					msg: "缺少参数"
				})
			}
		}
		let _id = parms._id
		const swiper = db.collection('swiper');
		let set = {}
		let value = parms.value
		if (parms.key == 'vod_index') value = parseInt(parms.value)
		set[parms.key] = value
		let data = await swiper.doc(_id).update(set);
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(data)
		}
	},
	async editClass(parms) {
		let userdata = await tokenCheck(this)
		if (!userdata.power) {
			return userdata
		}
		let httpInfo = this.getHttpInfo()
		let body = JSON.parse(httpInfo.body)
		let class_ = []
		if (body.class) class_ = body.class || null
		else class_ = parms.class || null
		if (!class_) {
			return {
				mpserverlessComposedResponse: true,
				statusCode: 403,
				body: JSON.stringify({
					msg: "缺少参数"
				})
			}
		}
		const collection = db.collection('configs');
		let data = await collection.where({
			name: 'class'
		}).update({
			value: class_
		})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify({
				msg: 'ok'
			})
		}
	},
	async pushVideo(parms) {
		let httpInfo = this.getHttpInfo()
		let body = JSON.parse(httpInfo.body)
		let {
			list,
			user,
			password
		} = body
		if (list.length == 0) {
			return {
				code: 200
			}
		}
		let userdata = (await collection.where({
			userid: user,
			password: password
		}).get()).data
		if (userdata.length == 0) {
			return {
				code: 403
			}
		}
		const videoclt = db.collection('videos');
		try {
			for (let v of list) {
				let dbd = (await videoclt.where({
					vod_id: v.vod_id
				}).get()).data
				let has = dbd.length != 0;
				dbd = dbd[0]
				if (!has) {
					await videoclt.add(v)
				} else {
					await videoclt.doc(dbd._id).set(v)
				}
			}
		} catch (e) {
			return {
				code: 100,
				msg: 'ok'
			}
			//TODO handle the exception
		}
		return {
			code: 200,
			msg: 'ok'
		}
	},
	async getUsers(parms) {
		let userdata = await tokenCheck(this)
		if (!userdata.power) {
			return userdata
		}
		let {
			page,
			count,
			user
		} = parms
		let search = {}
		if (user) search['user'] = user
		const collection = db.collection('users');
		let data = (await collection.where(search).limit(parseInt(count)).skip(parseInt(page) * parseInt(count))
			.get()).data
		let count_ = await collection.where(search).count()
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify({
				msg: 'ok',
				code: 200,
				list: data,
				count: count_.total
			})
		}
	},
}